import store from '../../store'

function webSocket (onsuccess) {
  this.wsUrl = store.state.Config.wss_url
  this.lockReconnect = false
  this.createWebSocket()
  this.success = onsuccess
}

webSocket.prototype.createWebSocket = function () {
  this.ws = new WebSocket(this.wsUrl)
  this.init()
}
webSocket.prototype.init = function () {
  var _this = this
  this.ws.onclose = function () {
    // console.log('链接关闭')
    _this.reconnect(_this.wsUrl)
  }
  this.ws.onerror = function () {
    // console.log('发生异常了')
    _this.reconnect(_this.wsUrl)
  }
  this.ws.onopen = function () {
    // console.log('链接正常')
    _this.success()
  }
  this.ws.onmessage = function (data) {
    data = JSON.parse(data.data)
    _this.onmsg && _this.onmsg(data.event, data.data)
  }
}
webSocket.prototype.reconnect = function reconnect (url) {
  var _this = this
  if (_this.lockReconnect) {
    return
  }
  _this.lockReconnect = true
  // 没连接上会一直重连，设置延迟避免请求过多
  let tt
  tt && clearTimeout(tt)
  tt = setTimeout(function () {
    _this.createWebSocket(url)
    _this.lockReconnect = false
  }, 4000)
}
webSocket.prototype.emit = function (eventName, data) {
  this.ws.send(JSON.stringify({
    event: eventName,
    data: data
  }))
}

export default webSocket
